package cn.com.surker.material.service.impl;

import cn.com.surker.common.MessageCenterException;
import cn.com.surker.enums.material.MaterialContractTypeEnum;
import cn.com.surker.enums.system.DataBaseEnum;
import cn.com.surker.enums.system.SupplierTypeEnum;
import cn.com.surker.material.dao.MainMaterialContractPriceDao;
import cn.com.surker.material.entity.MainMaterialContractPrice;
import cn.com.surker.material.entity.MainMaterialExaminePrice;
import cn.com.surker.material.dao.MainMaterialExaminePriceDao;
import cn.com.surker.material.service.MaterialExaminePriceBaseService;
import cn.com.surker.oa.dao.OaMaterialDao;
import cn.com.surker.oa.dao.OaSupplierDao;
import cn.com.surker.oa.entity.OaMaterial;
import cn.com.surker.oa.entity.OaSupplier;
import cn.com.surker.spring.RestResultDto;
import cn.com.surker.system.dao.DataSourceInfoDao;
import cn.com.surker.system.entity.DataSourceInfo;
import cn.com.surker.util.DateUtil;
import cn.com.surker.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import javax.annotation.Resource;
import java.util.*;

/**
* <p>
    * 原材价格审核表 服务实现类
    * </p>
*
* @author admin
* @since 2025-01-10
*/
public abstract class MaterialExaminePriceBaseServiceImpl extends ServiceImpl<MainMaterialExaminePriceDao, MainMaterialExaminePrice> implements MaterialExaminePriceBaseService {

    @Resource
    protected MainMaterialExaminePriceDao examinePriceDao;
    @Resource
    protected DataSourceInfoDao dsDao;
    @Resource
    protected OaMaterialDao materialDao;
    @Resource
    protected MainMaterialContractPriceDao contractPriceDao;
    @Resource
    protected OaSupplierDao supplierDao;

    /**
     * 云端分页查询
     * @param searchVal
     * @param orgId
     * @param supplierId
     * @param materialId
     * @param startTime
     * @param endTime
     * @param type
     * @param offset
     * @param limit
     * @return
     */
    public IPage findCloudPage(String searchVal, Long orgId, Long supplierId, Long transportId, Long materialId, String today,
                               String startTime, String endTime, Integer type, Integer offset, Integer limit) {
//        DataSourceInfo ds = dsDao.queryDSByOriginId(orgId);
//        if (ds == null || ds.getStatus() == 1 || ds.getType() != 0)
//            throw new MessageCenterException("ERP数据源错误");
        QueryWrapper<MainMaterialExaminePrice> examineQuery = initFullParam(searchVal, orgId, supplierId,
                transportId, materialId, today, startTime, endTime, type);
        PageHelper.offsetPage(offset, limit);
        IPage<MainMaterialExaminePrice> iPage = examinePriceDao.findCloudPage(new Page<>((offset + limit) /limit, limit), examineQuery);
        /**分页插件**/
        if (!StringUtils.isNull(iPage.getRecords())) {
            PageInfo pageInfo = new PageInfo(iPage.getRecords());
            if (!StringUtils.isNull(pageInfo.getTotal()))
                iPage.setTotal(pageInfo.getTotal());
        }
        return iPage;
    }

    /**
     * 按条件查询数据,价格审核表导出按此接口来
     * @param searchVal
     * @param orgId
     * @param supplierId
     * @param materialId
     * @param today
     * @param startTime
     * @param endTime
     * @param type
     * @return
     */
    public List<MainMaterialExaminePrice> findCloudData(String searchVal, Long orgId, Long supplierId, Long transportId, Long materialId,
                                                 String today, String startTime, String endTime, Integer type) {
//        DataSourceInfo ds = dsDao.queryDSByOriginId(orgId);
//        if (ds == null || ds.getStatus() == 1 || ds.getType() != 0)
//            throw new MessageCenterException("ERP数据源错误");
        QueryWrapper<MainMaterialExaminePrice> examineQuery = initFullParam(searchVal, orgId, supplierId,
                transportId, materialId, today, startTime, endTime, type);
        List<MainMaterialExaminePrice> examinePriceList = examinePriceDao.findCloudPage(examineQuery);
        if (examinePriceList == null || examinePriceList.size() == 0)
            return null;
        return examinePriceList;
    }
    /**
     * 查询是否已审核
     * @param orgId
     * @param today
     * @return
     */
    public Integer findCheck(Long orgId, String today) {
        if (StringUtils.isAllParamNull(orgId, today))
            throw new MessageCenterException("查询审核信息参数错误");
        Integer total = examinePriceDao.findCheckTotal(orgId, today, 1, null);
        if (total > 0)
            return total;
        total = examinePriceDao.findCheckTotal(orgId, today, null, 1);
        if (total > 0)
            return total;
        return 0;
    }
    /**
     * 新增价格审核信息
     * @param examinePrice
     * @return
     */
    public RestResultDto saveExaminePrice(MainMaterialExaminePrice examinePrice) {
        if (examinePrice == null || StringUtils.isNull(examinePrice.getOrgId()))
            throw new MessageCenterException("参数错误");
        if (examinePrice == null || StringUtils.isNull(examinePrice.getType()))
            throw new MessageCenterException("合同类型错误");
        if (examinePrice == null || StringUtils.isNull(examinePrice.getSupplierId()))
            throw new MessageCenterException("供应商信息错误");
        if (examinePrice == null || StringUtils.isNull(examinePrice.getMaterialId()))
            throw new MessageCenterException("材料信息错误");
        DataSourceInfo ds = dsDao.queryDSByOriginIdV1(examinePrice.getOrgId(), DataBaseEnum.MYSQL.getCode());
        if (ds == null || ds.getStatus() == 1 || ds.getType() != 0)
            throw new MessageCenterException("ERP数据源错误");
        if (examinePrice.getType().intValue() == MaterialContractTypeEnum.YSC.getCode().intValue()
            ||examinePrice.getType().intValue() == MaterialContractTypeEnum.YSS.getCode().intValue()) {
            if (examinePrice == null || StringUtils.isNull(examinePrice.getTransportId()))
                throw new MessageCenterException("运输合同请选择运输供应商");
        }
        examinePrice.setIsAuto(1);
        examinePrice.setCreateTime(new Date());
        Integer code = examinePriceDao.insert(examinePrice);
        if (code > 0) {
            return RestResultDto.success("新增成功~！");
        }
        throw new MessageCenterException("新增错误~！");
    }

    /**
     * 修改价格审核信息
     * @param examinePrice
     * @return
     */
    public RestResultDto updateExaminePrice(MainMaterialExaminePrice examinePrice) {

        return null;
    }

    /**
     * 修改价格审核信息状态
     * @param id
     * @param orgId
     * @param status
     * @param creator
     * @return
     */
    public RestResultDto updateStatus(Long id, Long orgId,String today, Long supplierId, Long materialId,
                                      Integer status, String creator) {
        if (StringUtils.isNull(id)) {
            if (StringUtils.isAllParamNull(orgId, today))
                throw new MessageCenterException("参数错误");
        }

        Date nowDate = new Date();
        if (!StringUtils.isNull(id)) {
            MainMaterialExaminePrice examinePrice = examinePriceDao.selectById(id);
            if (examinePrice == null)
                throw new MessageCenterException("数据不存在~!");
            if ((!StringUtils.isNull(examinePrice.getIsCheck()) && examinePrice.getIsCheck() == 1)
                || (!StringUtils.isNull(examinePrice.getIsFinance()) && examinePrice.getIsFinance() == 1))
                throw new MessageCenterException("已审核的数据不支持作废~!");
            examinePrice.setStatus(status);
            examinePrice.setUpdateTime(nowDate);
            examinePrice.setUpdator(creator);
            examinePrice.setRemark(creator + "作废价格信息");
            Integer code = examinePriceDao.updateById(examinePrice);
            if (code > 0)
                return RestResultDto.success("更新成功");
        } else {
            UpdateWrapper<MainMaterialExaminePrice> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("status", status);
            updateWrapper.set("updator", creator);
            updateWrapper.set("update_time", nowDate);
            updateWrapper.eq("org_id", orgId);
            updateWrapper.eq("today", today);
            updateWrapper.eq("is_check", 0);
            updateWrapper.eq("is_finance", 0);
            if (!StringUtils.isNull(supplierId))
                updateWrapper.eq("supplier_id", supplierId);
            if (!StringUtils.isNull(materialId))
                updateWrapper.eq("material_id", materialId);
            Integer code = examinePriceDao.update(new MainMaterialExaminePrice(), updateWrapper);
            if (code > 0)
                return RestResultDto.success("更新成功");
        }
        throw new MessageCenterException("更新失败");
    }

    /**
     * 审核价格表
     * @param orgId
     * @param today
     * @param isCheck
     * @param creator
     * @return
     */
    public RestResultDto examinePrice(Long orgId, String today, Integer isCheck, String creator) {
        if (StringUtils.isAllParamNull(orgId, today, isCheck))
            throw new MessageCenterException("参数错误");
        QueryWrapper<MainMaterialExaminePrice> query = new QueryWrapper<>();
        query.eq("org_id", orgId);
        query.eq("today", today);
        query.eq("status", 0);
        Integer total = examinePriceDao.selectCount(query);
        if (total < 1)
            throw new MessageCenterException("没有需要审核的数据");

        UpdateWrapper<MainMaterialExaminePrice> uw = new UpdateWrapper<>();
        Date nowDate = new Date();
        uw.set("is_check", isCheck);
        uw.set("checker", creator);
        uw.set("check_time", DateUtil.convertString(nowDate));
        uw.set("update_time", DateUtil.convertString(nowDate));
        uw.eq("org_id", orgId);
        uw.eq("status", 0);
        uw.eq("today", today);
        Integer code = examinePriceDao.update(new MainMaterialExaminePrice(), uw);
        if (code > 0)
            return RestResultDto.success("审核成功");

        return RestResultDto.fail("审核失败");
    }

//    /**
//     * 计算供应商主材价格审核报表信息
//     * @param today 结算月份
//     * @param supplierId 供应商ID
//     * @param materialId 材料ID
//     * @param creator
//     * @return
//     */
//    public RestResultDto calcExaminePrice(String today, Long orgId, String orgName, Long supplierId, Long materialId, String startTime,
//                                   String endTime, String creator) {
//        if (StringUtils.isAllParamNull(orgId, today, startTime, endTime))
//            throw new MessageCenterException("参数错误");
//        List<MainMaterialExaminePrice> supplierWeightList = examinePriceDao.findWeightSupplier(orgId, supplierId,
//                materialId, startTime, endTime);
//        if (supplierWeightList == null || supplierWeightList.size() == 0)
//            throw new MessageCenterException("未获取到过磅供应商信息");
//        List<OaMaterial> materialList = materialDao.findByOrg(orgId, supplierId);
//        Map<Long, OaMaterial> materialMap = new HashMap<>();
//        if (materialList == null || materialList.size() == 0)
//            throw new MessageCenterException("未获取到材料信息信息");
//        for (int i = 0; i < materialList.size(); i++) {
//            OaMaterial oaMaterial = materialList.get(i);
//            materialMap.put(oaMaterial.getId(), oaMaterial);
//        }
//        Map<Long, OaSupplier> supplierMap = new HashMap<>();
//        if (!StringUtils.isNull(supplierId)) {
//            OaSupplier supplier = supplierDao.selectById(supplierId);
//            if (supplier == null || supplier.getStatus() == 1)
//                throw new MessageCenterException("供应商不存在或已被禁用");
//            supplierMap.put(supplier.getId(), supplier);
//        } else {
//            List<OaSupplier> supplierList = supplierDao.queryByOrgV1(orgId, SupplierTypeEnum.CL.getCode());
//            if (supplierList == null || supplierList.size() == 0)
//                throw new MessageCenterException("未获取到供应商信息");
//            for (int i = 0; i < supplierList.size(); i++) {
//                OaSupplier supplier = supplierList.get(i);
//                supplierMap.put(supplier.getId(), supplier);
//            }
//        }
//        Date nowDate = new Date();
//        List<MainMaterialExaminePrice> examinePriceList = new ArrayList<>();
//        for (int i = 0; i < supplierWeightList.size(); i++) {//查询材料供应商单价信息
//            MainMaterialExaminePrice examinePrice = supplierWeightList.get(i);
//            Long tempSupplierId = examinePrice.getSupplierId();
//            Long tempMaterialId = examinePrice.getMaterialId();
//            String tempSupplier = "";
//            String tempMaterial = "";
//            Double tempLastPrice = 0.0;
//            Double tempPrice = 0.0;
//            Double tempLastTransportPrice = 0.0;
//            Double tempTransportPrice = 0.0;
//            String takeTime_ = "";
//            String remark = "";
//            if (supplierMap.get(tempSupplierId) != null)//供应商名称
//                tempSupplier = supplierMap.get(tempSupplierId).getFullName();
//            if (materialMap.get(tempMaterialId) != null)//材料名称
//                tempMaterial = materialMap.get(tempMaterialId).getFullName();
//
//            List<MainMaterialContractPrice> contractPriceList = contractPriceDao.findTakeTimeContractPrice(orgId,
//                    tempSupplierId, null, tempMaterialId, 0, startTime, endTime);
//            if (contractPriceList == null || contractPriceList.size() == 0) {//如果没得调价，查询上月最新价格
//                contractPriceList = contractPriceDao.findTakeTimeContractPrice(orgId,
//                        tempSupplierId, null, tempMaterialId, 0, null, startTime);
//                if (contractPriceList == null || contractPriceList.size() == 0)
//                    continue;
//                MainMaterialContractPrice tempContractPrice = contractPriceList.get(0);
//                tempLastPrice = tempContractPrice.getPrice();
//                tempPrice = tempContractPrice.getPrice();
//                takeTime_ = DateUtil.convertString(tempContractPrice.getTakeTime());
//                remark = tempContractPrice.getRemark();
//                MainMaterialExaminePrice materialExaminePrice = new MainMaterialExaminePrice(orgId, orgName, tempSupplierId,
//                        tempSupplier, null, null, today, startTime, endTime, tempMaterialId,
//                        tempMaterial, takeTime_, tempLastPrice, tempLastTransportPrice,
//                        tempPrice, tempTransportPrice, 0, 0, "");
//                materialExaminePrice.setRemark(remark);
//                materialExaminePrice.setCreateTime(nowDate);
//                materialExaminePrice.setStatus(0);
//                examinePriceList.add(materialExaminePrice);
//            } else {
//                List<MainMaterialContractPrice> lastContractPriceList = contractPriceDao.findTakeTimeContractPrice(orgId,
//                        tempSupplierId, null, tempMaterialId, 0, null, startTime);
//                if (lastContractPriceList != null && lastContractPriceList.size() > 0) {
//                    MainMaterialContractPrice tempContractPrice = contractPriceList.get(0);
//                    tempLastPrice = tempContractPrice.getPrice();
//                }
//                for (int j = 0; j < contractPriceList.size(); j++) {
//                    MainMaterialContractPrice tempContractPrice = contractPriceList.get(j);
//                    tempPrice = tempContractPrice.getPrice();
//                    remark = tempContractPrice.getRemark();
//                    takeTime_ = DateUtil.convertString(tempContractPrice.getTakeTime());
//                    MainMaterialExaminePrice materialExaminePrice = new MainMaterialExaminePrice(orgId, orgName, tempSupplierId,
//                            tempSupplier, null, null, today, startTime, endTime, tempMaterialId,
//                            tempMaterial, takeTime_, tempLastPrice, tempLastTransportPrice,
//                            tempPrice, tempTransportPrice, 0, 0, "");
//                    materialExaminePrice.setRemark(remark);
//                    materialExaminePrice.setCreateTime(nowDate);
//                    materialExaminePrice.setStatus(0);
//                    examinePriceList.add(materialExaminePrice);
//                }
//            }
//        }
//        if (examinePriceList == null ||examinePriceList.size() == 0)
//            throw new MessageCenterException("未获取到需更新的审核价格信息");
//        List<Object[]> insertList = new ArrayList();
//        List<Object[]> updateList = new ArrayList();
//        String nowTime = DateUtil.convertString(nowDate);
//        for (int i = 0; i < examinePriceList.size(); i++) {
//            MainMaterialExaminePrice tempExamine = examinePriceList.get(i);
//            MainMaterialExaminePrice examinePrice = examinePriceDao.findTodayExist(orgId,
//                    tempExamine.getSupplierId(), null, tempExamine.getMaterialId(),
//                    today, tempExamine.getTakeTime(), 0);
//            if (examinePrice == null) {
//                Integer resultCode = examinePriceDao.insert(tempExamine);
//                if (resultCode > 0) {
//                    Object[] objs = {tempExamine.getId(),orgId,tempExamine.getOrgName(),
//                            tempExamine.getSupplierId(),tempExamine.getSupplier(),null,"",today,startTime,
//                            endTime,tempExamine.getMaterialId(),tempExamine.getMaterial(),
//                            tempExamine.getTakeTime(),tempExamine.getLastPrice(),tempExamine.getLastTransportPrice(),
//                            tempExamine.getPrice(),tempExamine.getTransportPrice(),0,0,0,tempExamine.getPriceRemark(),
//                            tempExamine.getRemark(),creator,nowTime,"",nowTime};
//                    insertList.add(objs);
//                }
//            } else {
//                if (!StringUtils.isNull(examinePrice.getIsCheck()) && examinePrice.getIsCheck() == 1)
//                    continue;//如果审核了则不更新
//                examinePrice.setOrgName(tempExamine.getOrgName());
//                examinePrice.setSupplier(tempExamine.getSupplier());
//                examinePrice.setStartTime(startTime);
//                examinePrice.setEndTime(endTime);
//                examinePrice.setMaterial(tempExamine.getMaterial());
//                examinePrice.setLastPrice(tempExamine.getLastPrice());
//                examinePrice.setPrice(tempExamine.getPrice());
//                examinePrice.setPriceRemark(tempExamine.getPriceRemark());
//                examinePrice.setRemark(tempExamine.getRemark());
//                examinePrice.setUpdator(creator);
//                examinePrice.setUpdateTime(nowDate);
//                Integer resultCode = examinePriceDao.updateCloud(examinePrice);
//                if (resultCode > 0) {
//                    Object[] objs = {tempExamine.getOrgName(),tempExamine.getSupplier(),startTime,endTime,
//                            tempExamine.getMaterial(),tempExamine.getLastPrice(),tempExamine.getPrice(),
//                            tempExamine.getPriceRemark(),tempExamine.getRemark(),creator,nowTime,examinePrice.getId(),orgId};
//                    updateList.add(objs);
//                }
//            }
//        }
//
//        return RestResultDto.success("同步完成,请5分钟后刷新再试~！");
//    }
//
//    /**
//     * 计算供应商运输价格审核报表信息
//     * @param today 结算月份
//     * @param supplierId 供应商ID
//     * @param materialId 材料ID
//     * @param creator
//     * @return
//     */
//    public RestResultDto calcTransportExaminePrice(String today, Long orgId, Long supplierId, Long transportId, Long materialId,
//                                            String startTime, String endTime, String creator) {
//
//        return null;
//    }

    private QueryWrapper<MainMaterialExaminePrice> initFullParam(String searchVal, Long orgId, Long supplierId,
                   Long transportId,Long materialId, String today, String startTime, String endTime, Integer type) {
        QueryWrapper<MainMaterialExaminePrice> query = new QueryWrapper<>();
        query.eq("status", 0);
        if (!StringUtils.isNull(today))
            query.eq("today", today);
        if (!StringUtils.isNull(orgId))
            query.eq("org_id", orgId);
        if (!StringUtils.isNull(supplierId))
            query.eq("supplier_id", supplierId);
        if (!StringUtils.isNull(transportId))
            query.eq("transport_id", transportId);
        if (!StringUtils.isNull(materialId))
            query.eq("material_id", materialId);
        if (!StringUtils.isNull(startTime))
            query.ge("start_time", startTime);
        if (!StringUtils.isNull(endTime))
            query.lt("start_time", endTime);
        if (!StringUtils.isNull(type))
            query.eq("type", type);
        if (!StringUtils.isNull(searchVal))
            query.and(orderWrapper -> orderWrapper.like("supplier", searchVal).or()
                    .like("material", searchVal).or().like("remark", searchVal)
                    .or().like("transport", searchVal).or().like("price_remark", searchVal)
                    .or().like("link_man", searchVal));
        query.orderByDesc("today", "material_id");
        query.orderByAsc("supplier_id", "transport_id");
        query.orderByDesc("take_time");
        return query;
    }

}